package com.example.myapplicationwork.viewmodel;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.example.myapplicationwork.model.LoginRequest;
import com.example.myapplicationwork.model.RegisterRequest;
import com.example.myapplicationwork.repository.AuthRepository;
import com.example.myapplicationwork.utils.SharedPreferencesUtil;

/**
 * 认证ViewModel
 * 处理登录、注册和自动登录的业务逻辑
 */
public class AuthViewModel extends AndroidViewModel {
    private static final String TAG = "AuthViewModel";
    private final AuthRepository repository;
    private final SharedPreferencesUtil preferencesUtil;

    // LiveData用于观察登录状态
    public MutableLiveData<Boolean> isLoading = new MutableLiveData<>(false);
    public MutableLiveData<String> message = new MutableLiveData<>();
    public MutableLiveData<Boolean> isLoginSuccess = new MutableLiveData<>(false);
    public MutableLiveData<Boolean> isAutoLoginSuccess = new MutableLiveData<>(false);
    public MutableLiveData<String> userId = new MutableLiveData<>();
    public MutableLiveData<String> userName = new MutableLiveData<>();

    public AuthViewModel(@NonNull Application application) {
        super(application);
        repository = new AuthRepository(application);
        preferencesUtil = SharedPreferencesUtil.getInstance(application);
    }

    /**
     * 登录方法
     */
    public void login(String email, String password, boolean isAutoLogin) {
        if (email.isEmpty() || password.isEmpty()) {
            message.setValue("请输入邮箱和密码");
            return;
        }

        // 确保在开始登录前将isLoginSuccess设置为false
        isLoginSuccess.setValue(false);
        isLoading.setValue(true);
        message.setValue("正在登录中...");
        Log.d(TAG, "开始登录流程，isLoginSuccess初始值: false");

        LoginRequest request = new LoginRequest(email, password);
        repository.login(request, new AuthRepository.LoginCallback() {
            @Override
            public void onSuccess(String token, String userEmail, String userIdStr, String userNameStr) {
                // 保存登录信息
                preferencesUtil.saveLoginInfo(token, userEmail, userIdStr, userNameStr, isAutoLogin);
                
                // 更新LiveData
                userId.setValue(userIdStr);
                userName.setValue(userNameStr);
                Log.d(TAG, "登录成功，即将设置isLoginSuccess为true");
                isLoginSuccess.setValue(true);
                message.setValue("登录成功");
                isLoading.setValue(false);
                
                Log.d(TAG, "登录成功: " + userNameStr);
            }

            @Override
            public void onFailure(String errorMessage) {
                Log.d(TAG, "登录失败，即将设置isLoginSuccess为false");
                message.setValue(errorMessage);
                isLoginSuccess.setValue(false);
                isLoading.setValue(false);
                
                Log.e(TAG, "登录失败: " + errorMessage);
            }
        });
    }

    /**
     * 注册方法
     */
    public void register(String email, String password) {
        if (email.isEmpty() || password.isEmpty()) {
            message.setValue("请输入邮箱和密码");
            return;
        }

        isLoading.setValue(true);
        message.setValue("正在注册中...");

        RegisterRequest request = new RegisterRequest(email, password);
        repository.register(request, new AuthRepository.RegisterCallback() {
            @Override
            public void onSuccess(String token, String userEmail, String userIdStr, String userNameStr) {
                // 保存登录信息
                preferencesUtil.saveLoginInfo(token, userEmail, userIdStr, userNameStr, false);
                
                // 更新LiveData
                userId.setValue(userIdStr);
                userName.setValue(userNameStr);
                isLoginSuccess.setValue(true);
                message.setValue("注册成功");
                isLoading.setValue(false);
                
                Log.d(TAG, "注册成功: " + userNameStr);
            }

            @Override
            public void onFailure(String errorMessage) {
                message.setValue(errorMessage);
                isLoginSuccess.setValue(false);
                isLoading.setValue(false);
                
                Log.e(TAG, "注册失败: " + errorMessage);
            }
        });
    }

    /**
     * 自动登录方法
     */
    public void autoLogin() {
        if (!preferencesUtil.isAutoLogin()) {
            isAutoLoginSuccess.setValue(false);
            return;
        }

        isLoading.setValue(true);
        message.setValue("正在自动登录...");

        repository.autoLogin(new AuthRepository.AutoLoginCallback() {
            @Override
            public void onSuccess(String token, String userEmail, String userIdStr, String userNameStr) {
                // 更新LiveData - 只设置isAutoLoginSuccess，不设置isLoginSuccess
                userId.setValue(userIdStr);
                userName.setValue(userNameStr);
                isAutoLoginSuccess.setValue(true);
                isLoading.setValue(false);
                
                Log.d(TAG, "自动登录成功: " + userNameStr);
            }

            @Override
            public void onFailure(String errorMessage) {
                // 自动登录失败，尝试刷新Token
                refreshToken();
            }
        });
    }

    /**
     * 刷新Token
     */
    private void refreshToken() {
        repository.refreshToken(new AuthRepository.TokenRefreshCallback() {
            @Override
            public void onSuccess(String newToken) {
                // 保存新Token
                preferencesUtil.saveToken(newToken);
                
                // 刷新成功后再次尝试自动登录
                autoLogin();
            }

            @Override
            public void onFailure(String errorMessage) {
                message.setValue(errorMessage);
                isAutoLoginSuccess.setValue(false);
                isLoading.setValue(false);
                
                Log.e(TAG, "自动登录失败: " + errorMessage);
            }
        });
    }

    /**
     * 退出登录方法
     */
    public void logout() {
        preferencesUtil.clearAllData();
        isLoginSuccess.setValue(false);
        isAutoLoginSuccess.setValue(false);
        userId.setValue(null);
        userName.setValue(null);
        message.setValue("已退出登录");
        
        Log.d(TAG, "退出登录成功");
    }

    /**
     * 检查是否可以自动登录
     */
    public boolean canAutoLogin() {
        return preferencesUtil.isAutoLogin() && preferencesUtil.isLoggedIn();
    }

    /**
     * 获取当前用户名
     */
    public String getCurrentUserName() {
        return preferencesUtil.getUserName();
    }

    /**
     * 获取当前用户ID
     */
    public String getCurrentUserId() {
        return preferencesUtil.getUserId();
    }

    /**
     * 获取当前用户邮箱
     */
    public String getCurrentUserEmail() {
        return preferencesUtil.getUserEmail();
    }
}